<template>
  <view class="u-page">
    <div class="userbjInfo" v-if="userInfo">
      <span class="name">{{userInfo.userName}}</span>
      <span class="bj">{{userInfo.className}}</span>
      <span class="date">{{dateStr}}</span>
    </div>

    <view class="qiandaoArea" v-if="currentEvent">
      <view class="legends">
        <view class="item" :class="{active: currentEvent && currentEvent.eventName == qd.eventName}">
          <text>{{qd.eventName}}{{qd.time}}</text>
          <text class="status">{{qd.showText}}</text>
        </view>
        <view class="item" :class="{active:  currentEvent && currentEvent.eventName == qt.eventName}">
          <text>{{qt.eventName}}{{qt.time}}</text>
          <text class="status">{{qt.showText}}</text>
        </view>
      </view>

      <view class="bigbtn" :class="{disabled: !(currentEvent.status == 0 && inRadius)}" @click="doDaka">{{currentEvent.eventName}} </view>

      <view class="position">
        <template v-if="inRadius"><u-icon name="map-fill" color="#73D29F" size="18"></u-icon>已进入考勤范围：{{kqfw.name}}</template>
        <template v-else><u-icon name="map-fill" color="#DF1111" size="18"></u-icon>未进入考勤范围：{{kqfw.name}}</template>
      </view>
      
      <!-- <view class="test" v-if="kqfw && lnglat">
        {{lnglat}} / {{distance}} <view></view>
        {{kqfw.center}} / {{kqfw.radius}}
      </view> -->
    </view>
  </view>
</template>
<script>
import getLocation from '@/utils/getLocation.js';
import { mapState, mapMutations } from "vuex";
import mathUtil from '@/utils/mathUtil.js'
import sceneMixins from "@/utils/sceneMixins";
import mytabbar from "@/components/tabbar/index.vue";
import {uniqBy} from 'lodash';
export default {
  options: { styleIsolation: "shared" },
  components: { mytabbar: mytabbar },
  mixins: [getLocation, sceneMixins],
  computed: {
    ...mapState(["lnglat", "userInfo", "openId", "characterType", 'globalConfig']),
  },
  data() {
    return {
		  dateStr: this.$Util.getFmtDate(new Date()),
      qd: '',
      qt: '',
      currentEvent: '',
      kqfw: '',
      inRadius: false,
      distance: 0
    };
  },
  filters: {
  },
  methods: {
    getMinutes: function (str) {
      var h = parseInt(str.split(':')[0]);
      var m = parseInt(str.split(':')[1]);
      return h * 60 + m;
    },
    doDaka: function () {
      var vm = this;
      var disabled = !(vm.currentEvent.status == 0 && vm.inRadius);
      if (!disabled) {
        var params = {ruleId: vm.kqfw.ruleId, type: vm.currentEvent.eventName};
        uni.showLoading({title: '请等待...'});
        vm.getAndLoad('保存打卡', '/mobile/teacher/api/v1/attendance/saveAttendance.jsp?' + vm.$Util.stringify(params), function (res) {
          uni.hideLoading();
          if (res.code == 0) {
            uni.showModal({
              title: '提示',
              content: res.msg || '打卡成功',
              showCancel: false,
              success: function(res2) {
                uni.navigateBack();
              }
            });
          } else {
            uni.showToast({title: res.msg || '打卡失败', icon: 'none'});
          }
        });
      }
    },
    updateQdQtObject: function () {
      var vm = this;
      vm.qdqtTimeout && (clearTimeout(vm.qdqtTimeout));
      var currentM = vm.getMinutes(vm.$Util.getFmtDate(new Date(), 'hh:mm'));
      if (vm.qd.did) {
        vm.qd.status = 1;
        vm.qd.showText = '已打卡 ' + vm.qd.reportTime;
      } else {
        let status = 0;
        let showText = '';
        let startM = vm.getMinutes(vm.qd.startTime);
        let endM = vm.getMinutes(vm.qd.endTime);
        if (currentM < startM) { // 未打卡 判断有没有开始
          status = -1;
          showText = '未到打卡时间';
        } else if (currentM > endM) {
          status = 2;
          showText = '缺卡';
        }
        vm.qd.status = status;
        vm.qd.showText = showText;
      }

      if (vm.qt.did) {
        vm.qt.status = 1;
        vm.qt.showText = '已打卡 ' + vm.qt.reportTime;
      } else {
        let status = 0;
        let showText = '';
        let startM = vm.getMinutes(vm.qt.startTime);
        let endM = vm.getMinutes(vm.qt.endTime);
        if (currentM < startM) { // 未打卡 判断有没有开始
          status = -1;
          showText = '未到打卡时间';
        } else if (currentM > endM) {
          status = 2;
          showText = '缺卡';
        }
        vm.qt.status = status;
        vm.qt.showText = showText;
      }

      if (vm.qd.status == 0) {
        vm.currentEvent = vm.qd;
      } else {
        vm.currentEvent = vm.qt;
      }
      // 10秒后刷新一下状态
      vm.qdqtTimeout = setTimeout(() => {
        vm.updateQdQtObject();
      }, 10 * 1000);
    },
    stopUpdateLocation: function () {
      uni.setKeepScreenOn({keepScreenOn: false});
      clearInterval(global.hymGjsbInterval);
      return this.stopListenUserLocation();
    },

    calculateDistance: function () {
      var vm = this;
      if (vm.kqfw && vm.lnglat) {
        var distance = mathUtil.getDistance(vm.lnglat[1], vm.lnglat[0], vm.kqfw.center[1], vm.kqfw.center[0]);
        vm.inRadius = distance <= vm.kqfw.radius;
        vm.distance = distance;
      }
    },

    logPosition() {
			var vm = this;
			vm.getUserLocation().then(res => {
				vm.setPosition(res);
        vm.calculateDistance();
			});
		},
    logPosition2(res) {
      var vm = this;
      vm.setPosition(res);
      if (vm.kqfw) {
        vm.calculateDistance();
      }
    }
  },
  onShow() {
    var vm = this;
    if (vm.uploadByListen) {
      vm.listenUserLocation(vm.logPosition2, false)
    } else {
      vm.logPosition();
      global.hymGjsbInterval = setInterval(() => {
        vm.logPosition();
      }, 15000);
    }
    uni.showLoading({title: '正在获取定位'});
    vm.failTime = 0;
    setInterval(function(){
      if (vm.lnglat) {
        uni.hideLoading();
        clearInterval(this);
      } else {
        vm.failTime++;
        if (vm.failTime >= 10) {
          uni.hideLoading();
          uni.showModal({
            title: '提示',
            content: '获取定位失败，请检查定位服务和定位权限是否打开',
            showCancel: false,
            success: function(res2) {
                uni.navigateBack();
            }
          });
        }
      }
    }, 500);
  },
  onLoad(options) {
    var vm = this;
    vm.waitVariable("token").then(() => {
      var taskType = options.taskType;
      vm.dateStr2 = vm.dateStr.replace(/-/g, '/') + ' ';
      vm.uploadByListen = wx.canIUse('startLocationUpdate');
      vm.getAndLoad('考勤配置', '/mobile/teacher/api/v1/attendance/getAttendanceRules.jsp?taskType=' + (taskType || '暑期培训'), function (res) {
        if (res.code != 0) {
          uni.showModal({
            title: '提示',
            content: res.msg || '无效的请求',
            showCancel: false,
            success: function(res2) {
              uni.navigateBack();
            }
          });
          return;
        }
        // 1 已签到
        // -1 未到时间
        // 0 时间有效 未签
        // 2 时间无效 未签
        var data = res.data;
        vm.qd = {
          time: data.signTime,                  // 08:00
          reportTime: data.signReportTime || '',
          startTime: data.signStartTime || '',
          endTime: data.signEndTime || '',
          status: 2,
          showText: '',
          eventName: '签到',
          did: data.sfyqd
        };
        vm.qt = {
          time: data.outTime,
          reportTime: data.outReportTime || '',
          startTime: data.outStartTime || '',
          endTime: data.outEndTime || '',
          status: 1,
          showText: '',
          eventName: '签退',
          did: data.sfyqt
        }

        vm.updateQdQtObject();

        vm.kqfw = {
          name: data.schoolName,
          center: [parseFloat(data.lng), parseFloat(data.lat)],
          radius: parseInt(data.range),
          ruleId: data.id
        };
        vm.calculateDistance();
        
      })
    });
  },
  destroyed() {
    this.qdqtTimeout && (clearTimeout(this.qdqtTimeout));
    clearTimeout(global.reloadInfoTimeout)
    this.stopUpdateLocation();
  }
};
</script>

<style lang="scss" scoped>
.u-page {
  height: 100vh;
  overflow-y: scroll;
}
.userbjInfo {
    background: #fff;
    height: 120rpx;
    padding: 30rpx;
    box-sizing: border-box;
    display: flex;
    align-items: baseline;
    .name {
        font-size: 20px;
        font-weight: bold;
        margin-top: 5px;
        display: inline-block;
    }
    .bj {
        color: #999999;
        font-size: 14px;
        margin-left: 5px;
    }
    .date {
      margin-left: auto;
    }
}
.qiandaoArea {
    background: #fff;
    border-radius: 20rpx;
    margin: 20rpx 30rpx;
    padding: 30rpx;
    .legends {
      display: flex;
      .item {
        background: #EDEDEE;
        border-radius: 10rpx;
        padding: 20rpx;
        display: flex;
        flex-direction: column;
        flex: 1;
        margin: 0 10rpx 0 10rpx;
        box-sizing: border-box;
        &.active {
          border: 1px solid #5BC68D;
        }
        .status {
          color: #999999;
          font-size: 26rpx;
          margin-top: 10rpx;
        }
      }
    }
    .bigbtn {
      width: 290rpx;
      height: 290rpx;
      background: linear-gradient(45deg, #64CD95, rgba(100,205,149,0.7));
      border-radius: 50%;
      color: #fff;
      font-size: 60rpx;
      letter-spacing: 5rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 100rpx auto;
      &.disabled {
        background: linear-gradient(45deg, #bdb7b7, #d8d0d0)
      }
    }
    .position {
      display: flex;
      align-items: center;
      font-size: 28rpx;
      color: #999999;
      margin: 0 60rpx;
      padding-bottom: 60rpx;
    }
}

</style>
